package com.resou.reader.mine.login;

import android.content.Context;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.fm.openinstall.OpenInstall;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.commom.Constant;
import com.resou.reader.data.Injection;
import com.resou.reader.data.ResouxsRepository;
import com.resou.reader.data.vip.model.VipPrivilege;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.utils.AppExecutors;
import com.resou.reader.utils.CacheUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.eventbus.RefreshStoreEvent;
import com.resou.reader.utils.log.RsLog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginPresenter extends ResouBasePresenter<ILoginContact.ILoginView> implements ILoginContact.ILoginPresenter {
    private UserService mService;
    private ResouxsRepository mRepository;
    private CountDownTimer timer;

    public LoginPresenter(ILoginContact.ILoginView view) {
        super(view);
        mService = Injection.provideUserService();
        mRepository = ResouxsRepository.getInstance();
    }

    @Override
    public void sendSMS(String phone) {
        if (TextUtils.isEmpty(phone)) {
            mView.toastMsg(ReSouApplication.getRSApplication().getString(R.string.user_phone_number_empty));
            return;
        }
        if (phone.length() != 11) {
            mView.toastMsg(ReSouApplication.getRSApplication().getString(R.string.user_phone_number_ill));
            return;
        }


        mService.smsSend(phone, Constant.SMS_SEND_TYPE_LOGIN)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Result result) {
                        mView.toastMsg(result.getMsg());
                        if (result.getCode() == 0) {
                            startCountDownTimer();
                            timer.start();//开始计时
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.toastMsg(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void startCountDownTimer() {
        if (timer == null) {
            timer = new CountDownTimer(60 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    if (mView != null) {
                        mView.updateVerifyText(ReSouApplication.getRSApplication().getString(R.string.user_get_code_until_finished) + millisUntilFinished / 1000 + ")", false);
                    } else {
                        timer.cancel();
                    }
                }

                @Override
                public void onFinish() {
                    mView.updateVerifyText(ReSouApplication.getRSApplication().getString(R.string.user_login_get_code), true);
                }
            };
        }
    }

    @Override
    public void onViewDismiss() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /***
     *账号合并
     * @param state    状态 0：手机登录、1：微信登录、2：qq登录
     * @param account  账号
     * @param platform 平台
     */
    @Override
    public void mergeAccount(int state, String account, SHARE_MEDIA platform) {
        mService.mergeAccount(UserInstance.getToken(),
                state == 0 ? account : null, state == 1 ? account : null, state == 2 ? account : null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result<String> stringResult) {
                        switch (state) {
                            case 0:
                                mView.phoneLogin();
                                break;
                            case 1:
                                mView.winXinLogin(platform);
                                break;
                            case 2:
                                mView.qqLogin(platform);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.hideProgress();
                    }

                    @Override
                    public void onComplete() {
                        mView.hideProgress();
                    }
                });
    }

    /***
     *
     * @param mobile        电话号码
     * @param code          验证码
     */
    @Override
    public void smsLogin(String mobile, String code) {
        mService.smsLogin(DeviceUtils.getIMEI(ReSouApplication.getRSApplication()), mobile, code, "", Constant.LOGIN_TYPE_CODE, "android")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResult<LoginData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginResult<LoginData> loginDataLoginResult) {
                        if (loginDataLoginResult.getCode() == 0) {
                            String token = loginDataLoginResult.getToken();
                            if (token != null) {
                                CacheUtils.clearAllCache(ReSouApplication.getRSApplication());
                                LoginData data = loginDataLoginResult.getData();
                                UserInstance.setLoginData(data);
                                UserInstance.setToken(token);
                                MobclickAgent.onProfileSignIn("phone_sms", String.valueOf(data.getId()));
                                MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "phone_sms");
                                uPshSetting(data.getId());
                                /**
                                 * 同步本地书架到服务器
                                 */
                                EventBus.getDefault().post(new Message());
                                PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveSubSidyStateValue(loginDataLoginResult.getData().getReadType());
                                //登录成功后让其他地方更新登录信息
                                MessageEvent event = new MessageEvent();
                                event.isLogin = true;
                                EventBus.getDefault().post(event);
                                EventBus.getDefault().post(new RefreshStoreEvent());
                                EventBus.getDefault().post(new VipPrivilege());
                                //用户注册成功后调用OpenInstall 注册量统计
                                OpenInstall.reportRegister();
                                syncActivityInfo(ReSouApplication.getRSApplication());
                                saveRechargeActivityState(ReSouApplication.getRSApplication());

                                mView.loginSuccess(loginDataLoginResult.getData());
                                mView.dismiss();
                            } else {
                                mView.showError(new Throwable(loginDataLoginResult.getMsg()));
                            }
                        } else {
                            mView.showError(new Throwable(loginDataLoginResult.getMsg()));

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.showError(new Throwable(e));
                        mView.hideProgress();
                    }

                    @Override
                    public void onComplete() {
                        mView.hideProgress();
                    }
                });
    }

    @Override
    public void login(SHARE_MEDIA platform, String loginType, String unionid, String sex, String name, String icon) {
        String imei = DeviceUtils.getIMEI(ReSouApplication.getRSApplication());
        mService.thirdLogin(imei, loginType, unionid, sex, name, icon, "android")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResult<LoginData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginResult<LoginData> loginDataLoginResult) {
                        CacheUtils.clearAllCache(ReSouApplication.getRSApplication());
                        String msg = loginDataLoginResult.getMsg();
                        String token = loginDataLoginResult.getToken();
                        LoginData data = loginDataLoginResult.getData();
                        EventBus.getDefault().post(new RefreshStoreEvent());
                        PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveSubSidyStateValue(loginDataLoginResult.getData().getReadType());

                        if (loginDataLoginResult.getCode() == 0 && token != null) {
                            //登录成功后保存登录信息
                            UserInstance.setLoginData(data);
                            UserInstance.setToken(token);
                            //用户注册成功后调用OpenInstall 注册量统计
                            OpenInstall.reportRegister();
                            //统计
                            if (platform == SHARE_MEDIA.WEIXIN) {
                                MobclickAgent.onProfileSignIn("WX", String.valueOf(data.getId()));
                                MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "WeiXin");
                            } else if (platform == SHARE_MEDIA.QQ) {
                                MobclickAgent.onProfileSignIn("QQ", String.valueOf(data.getId()));
                                MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "QQ");
                            }

                            uPshSetting(data.getId());
                            /**
                             * 同步本地书架到服务器
                             */
                            EventBus.getDefault().post(new Message());

                            //登录成功后让其他地方更新登录信息
                            MessageEvent event = new MessageEvent();
                            event.isLogin = true;
                            EventBus.getDefault().post(event);
                            EventBus.getDefault().post(new RefreshStoreEvent());
                            EventBus.getDefault().post(new VipPrivilege());
                            syncActivityInfo(ReSouApplication.getRSApplication());
                            saveRechargeActivityState(ReSouApplication.getRSApplication());
                            mView.loginSuccess(loginDataLoginResult.getData());
                        } else {
//                            if (loginListener != null)
//                                loginListener.onError(new Throwable(msg));
                            mView.toastMsg(msg + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.hideProgress();
                    }

                    @Override
                    public void onComplete() {
                        mView.hideProgress();
                    }
                });
    }

    @Override
    public void uPshSetting(int userId) {

    }

    /***
     *
     * @param context
     */
    @Override
    public void syncActivityInfo(Context context) {
        /**
         * 检测是否参加过十五日免费阅读活动
         */
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            if (UserInstance.isLogin()) {
                String token = UserInstance.getToken();
                Boolean isInActivity = mRepository.checkIsInActivity(token);
                if (isInActivity) {
                    //参加过活动
                    PreferenceUtil.getInstance(context.getApplicationContext()).setNeverShowFifteenDaysDialogState();
                } else {
                    //未参加过
                    //校验是否应该弹出窗口
                    Boolean shouldOpenDialog = mRepository.checkIsShouldOpenDialog(token, "android");
                    if (shouldOpenDialog) {
                        PreferenceUtil.getInstance(context.getApplicationContext()).setShowFifteenDaysDialog();
                    }
                }
            }
        });
    }

    /***
     * 从服务器读三天充值状态
     * @param context
     */
    @Override
    public void saveRechargeActivityState(Context context) {
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            Boolean isJoin = mRepository.checkRechargeActivity(UserInstance.getToken());
            Log.i("充值", "saveRechargeActivityState: " + isJoin);
            PreferenceUtil.getInstance(context).setShowRechargeDialogToday(!isJoin);
        });
    }
}
